﻿using MediatR;
using MyMES.Domain.zyy;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Command.Works;
using System.Reflection.Metadata;

namespace MyMES.Read.API.Application.Handler.Works
{
    public class GetWorksHandler : IRequestHandler<GetWordCommand, APIPaging<List<WorkOrder>>>
    {
        private readonly IBaseRepository<WorkOrder> repository;
        /// <summary>
        /// 生产工单
        /// </summary>
        /// <param name="repository"></param>
        public GetWorksHandler(IBaseRepository<WorkOrder> repository)
        {
            this.repository = repository;
        }

        public async Task<APIPaging<List<WorkOrder>>> Handle(GetWordCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIPaging<List<WorkOrder>> result = new APIPaging<List<WorkOrder>>();
                result.Code = APIEnum.查询成功;
                result.Msg = "显示成功";
                string sql = "select *  from WorkOrder where IsDlete=false ORDER BY WorkOrderId  DESC";
                var list = await repository.SelectAsync(sql);
                if (!string.IsNullOrEmpty(request.WorkOrderCoding))
                {
                    list = list.Where(x => x.WorkOrderCoding.Contains(request.WorkOrderCoding)).ToList();
                }

                if (!string.IsNullOrEmpty(request.WorkOrderName))
                {
                    list = list.Where(x => x.WorkOrderName.Contains(request.WorkOrderName)).ToList();
                }

                if (!string.IsNullOrEmpty(request.WorkOrderType))
                {
                    list = list.Where(x => x.WorkOrderType.Contains(request.WorkOrderType)).ToList();
                }
                if (!string.IsNullOrEmpty(request.ProductNumber))
                {
                    list = list.Where(x => x.ProductNumber.Contains(request.ProductNumber)).ToList();
                }
                if (!string.IsNullOrEmpty(request.ProductName))
                {
                    list = list.Where(x => x.ProductName.Contains(request.ProductName)).ToList();
                }

                if (!string.IsNullOrEmpty(request.CustomerCode))
                {
                    list = list.Where(x => x.CustomerCode.Contains(request.CustomerCode)).ToList();
                }
                if (!string.IsNullOrEmpty(request.CustomerNamwe))
                {
                    list = list.Where(x => x.CustomerNamwe.Contains(request.CustomerNamwe)).ToList();
                }
                result.TotalCount = list.Count;
                result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.size);
                list = list.Skip((request.index - 1) * request.size).Take(request.size).ToList();
                result.data = list;
                return result;
            }
            catch (Exception)
            {

                throw;
            }
           
        }
    }
}
